﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Newtonsoft.Json;
using System;
using UnityEngine.Rendering.Universal.Internal;
using System.Security.Cryptography;
using System.Text;
using System.Linq;

[Serializable]
public class SaveGameData
{
    public CharacterInfo characterInfo;
    public string title;
    [HideInInspector]
    public float savePosX;
    [HideInInspector]
    public float savePosY;
    [HideInInspector]
    public string path;
}

public class SaveGame 
{
    public static int saveIndex = 1;
    public static string rootPath { get { return Application.streamingAssetsPath + "/Save"; } }
    private static List<SaveGameData> m_saveInfo;
    public static List<SaveGameData> SaveInfo
    {
        get {
            ReadPlayerAllInfo();
            return m_saveInfo;
        }
    }

    internal static void ClearSave(SaveGameData saveInfo)
    {
        m_saveInfo.Remove(saveInfo);
        string file= Path.GetFileName(saveInfo.path);
        string path = rootPath + "/" + file;
        if (File.Exists(path))
        {
            File.Delete(path);
        }
#if UNITY_EDITOR

        path = rootPath + "/" + file + ".meta";
        if (File.Exists(path))
        {
            File.Delete(path);
        }
#endif

    }



    public static CustomEvent onSaveSuccessful=EventFactory.CreatCustomEvent();

    public static void SavePlayerInfo(CharacterInfo characterInfo,Transform transform,string title)
    {
        SaveGameData saveGame = new SaveGameData()
        {
            characterInfo = characterInfo,
            title = saveIndex + "、" + title,
            savePosX = transform.position.x,
            savePosY = transform.position.y,
            path = rootPath +"/"+ saveIndex + ".json"
        };
        saveIndex++;

        string s = JsonConvert.SerializeObject(saveGame);
        using (FileStream fs = new FileStream(saveGame.path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
            fs.Write(b,0,b.Length);
        }      
        if (onSaveSuccessful != null)
        {
            onSaveSuccessful.Invoke();
        }
    }


    public static void ReadPlayerAllInfo()
    {
        if (Directory.Exists(rootPath))
        {
            Directory.CreateDirectory(rootPath);
        }
        string[] paths= Directory.GetFiles(rootPath);
        if (paths.Length == 0) return;
        List<string> validPath = new List<string>();
        for (int i = 0; i < paths.Length; i++)
        {
            if (paths[i].EndsWith(".json"))
            {
                paths[i]=paths[i].Replace("\\", "/");
                validPath.Add(paths[i]);
            }
        }
       
        m_saveInfo = new List<SaveGameData>();
        saveIndex = validPath.Count+1;
        for (int i = 0; i < validPath.Count; i++)
        {
            SaveGameData loadPlayer = ReadJson(validPath[i]);
            m_saveInfo.Add(loadPlayer);
        }
    }
    static SaveGameData ReadJson(string path)
    {
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] data = new byte[fs.Length];
            if (data.Length==0)
                return null;
            fs.Read(data, 0, data.Length);
            byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
            string dataStr = System.Text.Encoding.UTF8.GetString(data);
            if (data[0] == bomBuffer[0]
                && data[1] == bomBuffer[1]
                && data[2] == bomBuffer[2])
            {
                int copyLength = data.Length - 3;
                byte[] dataNew = new byte[copyLength];
                Buffer.BlockCopy(data, 3, dataNew, 0, copyLength);
                dataStr = System.Text.Encoding.UTF8.GetString(dataNew);
            }
            return JsonConvert.DeserializeObject<SaveGameData>(dataStr);
        }
    }

    public static string GetSceneName(string title)
    {
        title = title.Split('、')[1];
        string sceneName="Level1";
        switch (title)
        {
            case "寂静森林":
                sceneName = "Level1";
                break;
            case "废弃哨塔":
                sceneName = "Level2";
                break;
        }
        return sceneName;
    }
}

